package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.lang.model.element.VariableElement;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
判断用户是否登录
登录则放行
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //HttpServletRequest继承ServletRequest
        //对request,response类型转换，不转换有些方法不能用
        //获取uri   requset.getRequestUri 在ServletRequest类型上么有
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        //1. 获取本次请求的URI
        String requestURI = req.getRequestURI();
        log.info("拦截到的请求为：{}",requestURI);

        //定义不要拦截的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2. 判断本次请求, 是否需要登录, 才可以访问
        boolean check = check(urls,requestURI);

        //3. 如果不需要，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            //放行
            filterChain.doFilter(req,res);
            //程序不需要往后进行了  此处的return非常关键,如果没有此时的return ,代码会有bug
            return;
        }

        //4. 若不在登录退出界面，判断登录状态，如果已登录，则直接放行
        if(req.getSession().getAttribute("employee") != null){
            log.info("用户已经登录,用户的id为:",req.getSession().getAttribute("employee"));

            //获取当前登录用户的id
            Long empId = (Long) req.getSession().getAttribute("employee");
            //向当前的线程对象绑定了id
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(req,res);
            return;
        }


        //判断前端用户是否登录
        if(req.getSession().getAttribute("user") != null){
            log.info("用户已经登录,用户的id为:",req.getSession().getAttribute("user"));

            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(req,res);
            return;
        }

        //5. 如果未登录, 则返回未登录结果
        //若走到这，说明本次访问的不是静态页面，不是在登录或退出，肯定访问的是一段Java代码而且还没有登录
        log.info("用户未登录");
        //设置本次响应内容类型和编码
        res.setContentType("application/json;charset=utf-8");
        //构建R对象，携带NOTLOGIN字符串
        R r = R.error("NOTLOGIN");
        //将r字符串转换为JSON字符串
        String s = JSON.toJSONString(r);
        res.getWriter().write(s);
        return;
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            //使用路径匹配器比较
            boolean match = PATH_MATCHER.match(url, requestURI);
            //若为true，则fangxing
            if(match){
                return true;
            }
        }
        return false;
    }
}
